﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

public class StringHelper
{
    #region 截取字符长度
    /// <summary>
    /// 截取字符长度
    /// </summary>
    /// <param name="inputString">字符</param>
    /// <param name="len">长度</param>
    /// <returns></returns>
    public static string CutString(string inputString, int len)
    {
        ASCIIEncoding ascii = new ASCIIEncoding();
        int tempLen = 0;
        string tempString = "";
        byte[] s = ascii.GetBytes(inputString);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }

            try
            {
                tempString += inputString.Substring(i, 1);
            }
            catch
            {
                break;
            }

            if (tempLen > len)
                break;
        }
        //如果截过则加上半个省略号 
        byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
        if (mybyte.Length > len)
            tempString += "...";
        return tempString;
    }
    #endregion

    #region 清除HTML标记
    public static string DropHTML(string Htmlstring)
    {
        //删除脚本  
        Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
        //删除HTML  
        Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
        //Htmlstring = HtmlEncode(Htmlstring).Trim();
        return Htmlstring.Trim();
    }
    #endregion

    #region 清除HTML标记且返回相应的长度
    public static string DropHTML(string Htmlstring, int strLen)
    {
        return CutString(DropHTML(Htmlstring), strLen);
    }
    #endregion

    #region 检查危险字符
    /// <summary>
    /// 检查危险字符
    /// </summary>
    /// <param name="strchar"></param>
    /// <returns></returns>
    public static string SafeSqlInput(string strchar)
    {
        if (string.IsNullOrEmpty(strchar))
        {
            return "";
        }
        string[] SqlArray = new string[] { "select", "update", "delete", "insert", " and ", "from", " declare", "cast", " exec", "set", " or ", "char" };
        int index = IndexOfAny(strchar, SqlArray, true);
        string str = index < 0 ? strchar : strchar.Substring(0, index);
        string[] strArray = new string[] {
        "+", "'", "--", "%", "^", "&", "?", "<", ">", "[", "]", "{", "}",
        "\"", ";", ":", "char(39)", "char(0)", "(", ")"
     };
        for (int i = 0; i < strArray.Length; i++)
        {
            str = str.Replace(strArray[i], "").ToString();
        }
        return str.Replace("@@", "@").ToString();
    }
    #endregion

    public static string GetQueryString(string[] keys = null)
    {
        if (keys == null) return HttpContext.Current.Request.QueryString.ToString();
        string qstr = "";
        foreach (string k in keys)
        {
            string v = HttpContext.Current.Request.QueryString[k];
            if (!string.IsNullOrEmpty(v))
                qstr += "&" + k + "=" + v;
        }
        return qstr.Trim('&');
    }
    #region 对Html编码解码

    public static string HtmlDecode(string str)
    {
        if (!string.IsNullOrEmpty(str))
        {
            str = str.Replace("<br>", "\n");
            str = str.Replace("&gt;", ">");
            str = str.Replace("&lt;", "<");
            str = str.Replace("&nbsp;", " ");
            str = str.Replace("&#39;", "'");
            str = str.Replace("&quot;", "\"");
        }
        return str;
    }

    public static string HtmlEncode(string str)
    {
        if (!string.IsNullOrEmpty(str))
        {
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace(" ", "&nbsp;");
            str = str.Replace("'", "&#39;");
            str = str.Replace("\"", "&quot;");
            str = str.Replace("\r\n", "<br>");
            str = str.Replace("\n", "<br>");
        }
        return str;
    }

    #endregion

    #region 判断是否为数字
    public static bool IsNumeric(string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return false;
        }
        int len = value.Length;
        if ('-' != value[0] && '+' != value[0] && !char.IsNumber(value[0]))
        {
            return false;
        }
        for (int i = 1; i < len; i++)
        {
            if (!char.IsNumber(value[i]))
            {
                return false;
            }
        }
        return true;
    }
    public static bool IsNumber(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return false;
        }
        return Regex.IsMatch(input, "^[0-9]+$");
    }
    public static bool IsNumberOrWhiteSpace(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return false;
        }
        return Regex.IsMatch(input, @"^[0-9\s\r\n]+$");
    }

    #endregion

    #region 为value加颜色标签
    public static object AddColor(object value, string color)
    {
        if (!string.IsNullOrEmpty(color))
        {
            return "<font color='" + color + "'>" + value + "</font>";
        }
        return value;
    }
    #endregion

    #region 获取有默认值的QueryString,并检查sql语句安全性
    public static string SafeNumberInput(string value)
    {
        return string.IsNullOrEmpty(value) ? "" : Regex.Replace(value, "[^0-9]", " ", RegexOptions.IgnoreCase);
    }
    public static string SafeNumberQuery(string Key, string DefaultValue)
    {
        return SafeNumberInput(QueryString(Key, DefaultValue));
    }
    public static string SafeSqlQuery(string key, string DefaultValue, bool cut = false)
    {
        return SafeSqlInput(QueryString(key, DefaultValue, cut));
    }
    public static string QueryString(string key, string DefaultValue, bool cut = false)
    {
        string Value = null;
        if (HttpContext.Current.Request.QueryString[key] != null)
            Value = HttpContext.Current.Request.QueryString.Get(key);
        if (string.IsNullOrWhiteSpace(Value)) Value = DefaultValue;
        if (cut && !string.IsNullOrEmpty(Value))
        {
            string[] Values = Value.Split(new char[] { ' ', ',', '-', '_' }, StringSplitOptions.RemoveEmptyEntries);
            Value = Values[0];
        }
        return Value;
    }

    public static string UrlEncode(string value)
    {
        return HttpUtility.UrlEncode(value, HttpContext.Current.Request.ContentEncoding);
    }
    private static byte[] GetHexByte(string hexString)
    {
        hexString = hexString.Replace(" ", "");
        if ((hexString.Length % 2) != 0)
            hexString += " ";
        byte[] returnBytes = new byte[hexString.Length / 2];
        for (int i = 0; i < returnBytes.Length; i++)
            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        return returnBytes;
    }
    private static string GetHexStr(byte[] bytes)
    {
        string returnStr = "";
        if (bytes != null)
        {
            for (int i = 0; i < bytes.Length; i++)
            {
                returnStr += bytes[i].ToString("X2");
            }
        }
        return returnStr;
    }
    public static string UrlEncrypt(string value)
    {
        try
        {
            return GetHexStr(Encoding.GetEncoding("gb2312").GetBytes(value));
        }
        catch
        {
            return "";
        }
    }
    public static string UrlDecrypt(string value)
    {
        try
        {
            return Encoding.GetEncoding("gb2312").GetString(GetHexByte(value));
        }
        catch
        {
            return "";
        }
    }
    #endregion

    #region 检测字符串中包含给定字符串数组中的任一值的最小索引。
    public static int IndexOfAny(string currentStr, string[] argStrs, bool attentionCase = true)
    {
        int Index = -1, minIndex = -1;
        foreach (string s in argStrs)
        {
            if (attentionCase)
                Index = currentStr.IndexOf(s, StringComparison.OrdinalIgnoreCase);
            else
                Index = currentStr.IndexOf(s, StringComparison.Ordinal);
            minIndex = Index < 0 ? minIndex : (minIndex < 0 ? Index : (minIndex < Index ? minIndex : Index));
        }
        return minIndex;
    }
    #endregion
}
